﻿using Furion.DependencyInjection;
using Furion.FriendlyException;
using GWB.Core.TableEntity;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;
using GWB.Supplier;
using GWB.Core.Common.Utils;

namespace GWB.System.Api.Handler
{

   // 全局错误拦截器
    /// <summary>
    /// 
    /// </summary>
    public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
    {
        /// <inheritdoc />
        public Task OnExceptionAsync(ExceptionContext ex)
        {
            if (!ex.ExceptionHandled)
            {
                Task.Run(() =>
                {
                    var isUnexpected = !ContainUtils.IsContainProperty(ex.Exception, "ErrorCode");

                    // 写日志
                    SqlSugarDb.Db.Insertable(new ErrorLog()
                    {
                        IsUnexpected = isUnexpected,
                        ErrorCode = isUnexpected ?"500"
                            : ContainUtils.GetContainPropertyValue(ex.Exception, "ErrorCode").ToString(),
                        ErrorMessage = ex.Exception.Message,
                        StackTrace = ex.Exception.StackTrace,
                    }).ExecuteCommandAsync();
                });
            }
            return Task.CompletedTask;
        }
    }
}
